//
//  UITextField+CXTextField.m
//  智积分
//
//  Created by apple on 2018/4/13.
//  Copyright © 2018年 Cynic. All rights reserved.
//

#import "UITextField+CXTextField.h"

@implementation UITextField (CXTextField)
static void *cx_fieldeventsBlock;
static void *maxKey;


-(void)setCX_FieldEventsBlock:(FieldEventsBlock)CX_FieldEventsBlock{
    objc_setAssociatedObject(self, &cx_fieldeventsBlock, CX_FieldEventsBlock, OBJC_ASSOCIATION_COPY);
}

-(FieldEventsBlock)CX_FieldEventsBlock{
    return objc_getAssociatedObject(self, &cx_fieldeventsBlock);
}

-(NSInteger)max{
    return [objc_getAssociatedObject(self, &maxKey) integerValue];
}

-(void)setMax:(NSInteger)max{
    objc_setAssociatedObject(self, &maxKey, [NSNumber numberWithInteger:max],OBJC_ASSOCIATION_ASSIGN);
}

-(void)cx_eventsChangeByHandler:(void (^)(void))block{
    self.CX_FieldEventsBlock = block;
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFieldEditChanged:)
                                                name:UITextFieldTextDidChangeNotification
                                              object:self];
}

-(void)textFieldEditChanged:(NSNotification *)noti{
    UITextField *textView = (UITextField *)noti.object;
    NSString *toBeString = textView.text;
    //获取高亮部分
    UITextRange *selectedRange = [textView markedTextRange];
    UITextPosition *position = [textView positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position)
    {
        
        if (toBeString.length > self.max)
        {
            NSRange rangeIndex = [toBeString rangeOfComposedCharacterSequenceAtIndex:self.max];
            if (rangeIndex.length == 1)
            {
                textView.text = [toBeString substringToIndex:self.max];
            }
            else
            {
                NSRange rangeRange = [toBeString rangeOfComposedCharacterSequencesForRange:NSMakeRange(0, self.max)];
                textView.text = [toBeString substringWithRange:rangeRange];
            }
            //            if (textView.text.length > 0) {
            //                self.PlaceHolder.hidden = YES;
            //            }
            //            else{
            //                self.PlaceHolder.hidden = NO;
            //            }
            
        }
        if (self.CX_FieldEventsBlock) {
            self.CX_FieldEventsBlock();
        }
    }
    
}

@end

